package login

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"src/db"
	"src/pojo"
	"src/util"
	"strconv"
)
// 登入
func Login(w http.ResponseWriter, r *http.Request)  {
	var auth pojo.Auth
	if err := json.NewDecoder(r.Body).Decode(&auth); err != nil{
		r.Body.Close()
		log.Fatal(err)
	}
	// 如果密码是明文
	md5userName := util.Md5(auth.Password)
	auth.Password = md5userName
	var result pojo.Resp
	fmt.Println(auth)
	// 数据库校验
	check := checkUser(auth)
	fmt.Println(check)
	result.Data = check
	if(check){
		result.Msg = "login success"
	}else {
		result.Msg = "login fail"
	}
	if err := json.NewEncoder(w).Encode(result); err != nil {
		log.Fatal(err)
	}
}

// 用户账号密码校验
func checkUser(auth pojo.Auth) bool  {
	conn, _ := db.Conn()
	var sql string
	sql = "select count(*) from t_user where user_name ='" + auth.UserName + "' and password = '" + auth.Password + "'"
	query, _ := conn.Query(sql)
	var flag string
	var count int
	for query.Next(){
		err := query.Scan(&flag)
		if err != nil {
			return false
		}
	}

	count,_ = strconv.Atoi(flag)

	if count > 0 {
		return true
	}

	return false
}
